package com.stefanini.worldcupinformation.ejbs;

import com.stefanini.worldcupinformationpersistence.entities.Equipo;
import com.stefanini.worldcupinformationpersistence.entities.Grupo;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@LocalBean
@Stateless
public class TeamDao {
    
    @PersistenceContext
    private EntityManager em;
    
    public void newTeam(Equipo team){
        try {
            em.persist(team);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Insertar el equipo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void edit(Equipo team){
        try {
            team.setGrupoId(em.getReference(Grupo.class, team.getGrupoId().getId()));
            em.merge(team);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Editar Equipo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void delte(Equipo team){
        try {
            team = em.merge(team);
            em.remove(team);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Eliminar Equipo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<Equipo> getAll(){
        List<Equipo> teams = new ArrayList<>();
        try {
            teams = em.createNamedQuery("Equipo.findAll").getResultList();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! GetAll Equipos", e);
        }
        return teams;
    }
    
}
